package com.example.administrator.printoutindemo.mvp.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.example.administrator.printoutindemo.R;
import com.example.administrator.printoutindemo.di.component.DaggerPanDianComponent;
import com.example.administrator.printoutindemo.di.module.PanDianModule;
import com.example.administrator.printoutindemo.mvp.contract.PanDianContract;
import com.example.administrator.printoutindemo.mvp.presenter.PanDianPresenter;
import com.example.administrator.printoutindemo.mvp.ui.adapter.SaoMiaoChaKanXiangQingAdapter;
import com.example.administrator.printoutindemo.mvp.ui.entity.GetMaterialDetailInfo;
import com.example.administrator.printoutindemo.mvp.ui.entity.PanDian;
import com.google.gson.Gson;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.xiaoxing.gifloadingview.LoadingDialogUtil;
import com.xiaoxing.zhinenghuacangku.mvp.ui.activity.ScanQRCodeActivity;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonres.view.RecycleViewDivider;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import pub.devrel.easypermissions.EasyPermissions;

import static com.jess.arms.base.BaseConstants.SCAN_REQUEST_CODE;
import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ACTIVITY_PAN_DIAN)
public class PanDianActivity extends BaseActivity<PanDianPresenter> implements PanDianContract.View, EasyPermissions.PermissionCallbacks {

    @BindView(R.id.btnRight)
    ImageView mBtnRight;
    @BindView(R.id.tv_xiang_mu)
    TextView tvXiangMu;
    @BindView(R.id.tv_wu_liao_ming_cheng)
    TextView tvWuLiaoMingCheng;
    @BindView(R.id.tv_he_tong_qian_ding_qi_qi)
    TextView tvHeTongQianDingQiQi;
    @BindView(R.id.tv_pei_song_ji_hua_ri_qi)
    TextView tvPeiSongJiHuaRiQi;
    @BindView(R.id.tv_dao_huo_shi_jian)
    TextView tvDaoHuoShiJian;
    @BindView(R.id.tv_ji_hua_shu_liang)
    TextView tvJiHuaShuLiang;
    @BindView(R.id.tv_ben_ci_dao_huo_shu_liang)
    TextView tvBenCiDaoHuoShuLiang;
    @BindView(R.id.tv_ku_cun_shu_liang)
    TextView tvKuCunShuLiang;
    @BindView(R.id.tv_gong_ying_shang)
    TextView tvGongYingShang;
    @BindView(R.id.tv_gong_ying_shang_lian_xi_ren)
    TextView tvGongYingShangLianXiRen;
    @BindView(R.id.tv_gong_ying_shang_lian_xi_dian_hua)
    TextView tvGongYingShangLianXiDianHua;
    @BindView(R.id.tv_bei_zhu)
    TextView tvBeiZhu;
    @BindView(R.id.tv_hui_shou_bao_fei_zhuang_tai)
    TextView tvHuiShouBaoFeiZhuangTai;
    @BindView(R.id.tv_hui_shou_bao_fei_shi_jian)
    TextView tvHuiShouBaoFeiShiJian;
    @BindView(R.id.tv_hui_shou_bao_fei_shu_liang)
    TextView tvHuiShouBaoFeiShuLiang;
    @BindView(R.id.tv_hui_shou_bao_fei_xiang_mu)
    TextView tvHuiShouBaoFeiXiangMu;
    @BindView(R.id.tv_hui_shou_bao_fei_cang_ku)
    TextView tvHuiShouBaoFeiCangKu;
    List<GetMaterialDetailInfo.OutStoreListBean> mOutStoreListBeans = new ArrayList<>();
    @BindView(R.id.tv_chu_ku_ji_lu)
    TextView tvChuKuJiLu;
    @BindView(R.id.tv_cang_wei)
    TextView tvCangWei;
    @BindView(R.id.tv_gui_ge)
    TextView tvGuiGe;
    @BindView(R.id.rb_pan_dian_wu_wu)
    RadioButton rbPanDianWuWu;
    @BindView(R.id.rg_pan_dian_you_wu)
    RadioButton rgPanDianYouWu;
    @BindView(R.id.rg_pan_dian)
    RadioGroup rgPanDian;
    @BindView(R.id.btn_ti_jiao)
    Button btnTiJiao;
    @BindView(R.id.tv_wu_liao_ming_cheng_ok)
    EditText tvWuLiaoMingChengOk;
    @BindView(R.id.tv_ku_cun_shu_liang_ok)
    EditText tvKuCunShuLiangOk;
    @BindView(R.id.ll_ok_pan_dian)
    LinearLayout llOkPanDian;

    private String mid;
    private String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
    private View.OnClickListener mRightListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (getPermission()) {

                toScanQRCodeActivity();
            }
        }
    };
    private SaoMiaoChaKanXiangQingAdapter mSaoMiaoChaKanXiangQingAdapter;
    private RecyclerView mRecyclerView;
    private String mCheckResult = "true"; //checkResult: "true"--表示盘点无误  material,nums 都传入空字符串
    //checkResult: "false"--表示盘点有问题  如果物料不对应  则传入material 不为空；如果数量不对应 则传入nums不为空
    // 如果都不对 则 material 和 nums都不为空
    private String mMaterial = "";
    private String mNums = "";

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerPanDianComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .panDianModule(new PanDianModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_pan_dian; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.activity_pan_dian));
//        getPanDianData();
        mBtnRight.setImageDrawable(getResources().getDrawable(R.drawable.icon_scan));
        mBtnRight.setOnClickListener(mRightListener);

        initRecyclerView();

        rgPanDian.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                switch (checkedId) {

                    case R.id.rb_pan_dian_wu_wu:
                        llOkPanDian.setVisibility(View.GONE);
                        break;
                    case R.id.rg_pan_dian_you_wu:
                        llOkPanDian.setVisibility(View.VISIBLE);

                        break;
                }
            }
        });
    }

    private void initRecyclerView() {
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        mRecyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL, 20, getResources().getColor(R.color.public_client_line_color)));
        mSaoMiaoChaKanXiangQingAdapter = new SaoMiaoChaKanXiangQingAdapter(this, mOutStoreListBeans);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setAdapter(mSaoMiaoChaKanXiangQingAdapter);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

        ArmsUtils.makeText(this, "相关权限获取成功");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "请同意相关权限，否则功能无法使用");

    }

    private boolean getPermission() {
        if (EasyPermissions.hasPermissions(this, permissions)) {
            return true;
        } else {
            EasyPermissions.requestPermissions(this, "需要获取您的照相使用权限", 103, permissions);
            return false;
        }

    }

    private void getPanDianData() {
        mPresenter.getPanDianData();
    }

    @Override
    public void getPanDianDataSuccess(PanDian entityData) {


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 101) {
            Bundle extras = data.getExtras();
            if (extras != null) {

                mid = extras.getString("scan_result");
                getScanData(mid);
            }

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        if (requestCode == 103) {
            toScanQRCodeActivity();
        }
    }

    private void toScanQRCodeActivity() {
        Intent newIntent = new Intent(PanDianActivity.this, ScanQRCodeActivity.class);
        mSharedPreferencesHelper.putInt(SCAN_REQUEST_CODE, 101);
        // 开始一个新的 Activity等候返回结果
        startActivityForResult(newIntent, 101);
    }

    /**
     * 盘点扫码显示信息
     *
     * @param mid
     */
    private void getScanData(String mid) {

        showLoading();

        String methodName = "checkInventoryMaterial";

        SoapUtil soapUtil = SoapUtil.getInstance(this);
        soapUtil.setDotNet(true);
        SoapParams params = new SoapParams();
        params.put("mid", mid);

        /**
         * 请求
         */
        soapUtil.callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty("checkInventoryMaterialResult").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {


                    Gson gson = new Gson();
                    GetMaterialDetailInfo getMaterialDetailInfo = gson.fromJson(result, GetMaterialDetailInfo.class);

                    if (getMaterialDetailInfo != null) {

                        tvXiangMu.setText(getMaterialDetailInfo.getProjectName());
                        tvWuLiaoMingCheng.setText(getMaterialDetailInfo.getMaterial());
                        tvHeTongQianDingQiQi.setText(getMaterialDetailInfo.getContractDate());
                        tvPeiSongJiHuaRiQi.setText(getMaterialDetailInfo.getDistributionDate());
                        tvDaoHuoShiJian.setText(getMaterialDetailInfo.getArriveDate());
                        tvJiHuaShuLiang.setText(getMaterialDetailInfo.getSupplyPlanNum());
                        tvBenCiDaoHuoShuLiang.setText(getMaterialDetailInfo.getArriveNum());
                        tvKuCunShuLiang.setText(getMaterialDetailInfo.getInventoryNum());
                        tvGongYingShang.setText(getMaterialDetailInfo.getSupplier());
                        tvGongYingShangLianXiRen.setText(getMaterialDetailInfo.getSupplierPeople());
                        tvGongYingShangLianXiDianHua.setText(getMaterialDetailInfo.getSupplierPhone());
                        tvBeiZhu.setText(getMaterialDetailInfo.getRemark());
                        tvHuiShouBaoFeiZhuangTai.setText(getMaterialDetailInfo.getRecoverOrScrapState());
                        tvHuiShouBaoFeiShuLiang.setText(getMaterialDetailInfo.getRecoverOrScrapNum());
                        tvHuiShouBaoFeiXiangMu.setText(getMaterialDetailInfo.getRecoverOrScrapProject());
                        tvHuiShouBaoFeiCangKu.setText(getMaterialDetailInfo.getRecoverOrScrapStore());
                        tvCangWei.setText(getMaterialDetailInfo.getSpname());
                        tvGuiGe.setText(getMaterialDetailInfo.getUnit());
//                        tvChuKuJiLu.setText(getMaterialDetailInfo.getOutStoreList());

                        if (getMaterialDetailInfo.getOutStoreList() != null && getMaterialDetailInfo.getOutStoreList().size() > 0) {
                            mOutStoreListBeans.clear();
                            mOutStoreListBeans.addAll(getMaterialDetailInfo.getOutStoreList());
                            mSaoMiaoChaKanXiangQingAdapter.notifyDataSetChanged();

                        }
                    }

                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());


    }

    @Override
    public void showLoading() {
        LoadingDialogUtil.showGifdialog2(getSupportFragmentManager(), R.drawable.public_loading);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtil.dismissDialog();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }


    @OnClick(R.id.btn_ti_jiao)
    public void onViewClicked() {
        if (TextUtils.isEmpty(mid)) {
            ArmsUtils.makeText(this, "请先扫描物料");
            toScanQRCodeActivity();
            return;
        }
        if (rbPanDianWuWu.isChecked()) {
            mCheckResult = "true";
            mMaterial = "";
            mNums = "";
        }
        if (rgPanDianYouWu.isChecked()) {
            mCheckResult = "false";
            if (TextUtils.isEmpty(tvWuLiaoMingChengOk.getText().toString()) && TextUtils.isEmpty(tvKuCunShuLiangOk.getText().toString())) {
                ArmsUtils.makeText(this, "请输入正确的物料名称或数量");
                return;
            }
//            if (TextUtils.isEmpty(tvKuCunShuLiangOk.getText().toString())) {
//                ArmsUtils.makeText(this, "正确的库存数量");
//                return;
//            }
            mMaterial = tvWuLiaoMingChengOk.getText().toString();
            mNums = tvKuCunShuLiangOk.getText().toString();
        }
        setInventoryMaterialCheckResult(mid, mCheckResult, mMaterial, mNums);
    }

    /**
     * 提交盘点结果
     *
     * @param mid
     */
    private void setInventoryMaterialCheckResult(String mid, String checkResult, String material, String nums) {

        showLoading();

        String methodName = "setInventoryMaterialCheckResult";

        SoapUtil soapUtil = SoapUtil.getInstance(this);
        soapUtil.setDotNet(true);
        SoapParams params = new SoapParams();
        params.put("mid", mid);
        params.put("checkResult", checkResult);
        params.put("material", material);
        params.put("nums", nums);

        /**
         * 请求
         */
        soapUtil.callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty("setInventoryMaterialCheckResultResult").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {


                    if (result.equals("True")) {
                        ArmsUtils.makeText(getContext(), "提交成功");
                        toScanQRCodeActivity();
                    } else {
                        ArmsUtils.makeText(getContext(), "提交失败");
                    }

                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());


    }
}
